package com.yfbao.horizon.encrypt.utils;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Hex;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class SHA1Utils {
    private static final String EN_CODING = "UTF-8";
    private static MessageDigest digest = null;

    static {
        try {
            digest = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e) {
            log.error("init sha1 digest error", e);
        }
    }

    /**
     * sha1加密
     *
     * @param clearText 明文str
     * @return
     */
    public static String encrypt(String clearText) {
        try {
            return encrypt(clearText.getBytes(EN_CODING));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * sha1 加密
     *
     * @param bytes 明文byte
     * @return
     */
    public static String encrypt(byte[] bytes) {
        return Hex.toHexString(encrypt2Byte(bytes));
    }

    /**
     * sha1加密
     *
     * @param bytes 明文byte
     * @return
     */
    public static byte[] encrypt2Byte(byte[] bytes) {
        try {
            synchronized (digest) {
                digest.update(bytes);
                return digest.digest();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
